package util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.servlet.http.HttpSession;

import model.User;

import common.Constants;

import exception.ConnectiontException;

public class JdbcUtil {

	public static Connection getConnection(String url, String userName,
			String password) throws ConnectiontException {
		Connection conn = null;
		try {
			Class.forName(Constants.ORACLE_DB_DRIVER);
			conn = DriverManager
					.getConnection(url, userName, password);
		} catch (ClassNotFoundException e) {
			throw new ConnectiontException(e.getMessage());
		} catch (SQLException e) {
			throw new ConnectiontException(e.getMessage());
		}
		return conn;
	}
	
	public static Connection getAdminConnection() throws ConnectiontException {
		Connection conn = null;
		try {
			Class.forName(Constants.MYSQL_DB_DRIVER);
			conn = DriverManager
					.getConnection(Constants.MYSQL_DB_URL, Constants.ADMIN_USER_NAME, Constants.ADMIN_USER_PASSWORD);
		} catch (ClassNotFoundException e) {
			throw new ConnectiontException(e.getMessage());
		} catch (SQLException e) {
			throw new ConnectiontException(e.getMessage());
		}
		return conn;
	}
	
	public static Connection getConnection(HttpSession session)
			throws ConnectiontException {
		if (session != null && session.getAttribute(Constants.KEY_CURRENT_USER) != null) {
			User currentUser = (User) session.getAttribute("currentUser");
			return getConnection(currentUser.getUrl(),
					currentUser.getUserName(), currentUser.getPassword());
		} else {
			throw new ConnectiontException("登录已失效");
		}
	}

	public static void closeConnection(Connection conn) {
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void rollbackConnection(Connection conn) {
		try {
			conn.rollback();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void commitConnection(Connection conn) {
		try {
			conn.commit();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		JdbcUtil.getConnection(Constants.ORACLE_DB_URL, Constants.ADMIN_USER_NAME, Constants.ADMIN_USER_PASSWORD);
	}
}
